package com.hxzy.controller.front.contamer;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.hxzy.common.controller.BaseController;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.resp.R;
import com.hxzy.controller.front.contamer.req.ContamerAddReq;
import com.hxzy.controller.front.mapstruct.ContamerConvert;
import com.hxzy.entity.Contamer;
import com.hxzy.service.ContamerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author wy
 * @Description 手机端-会员API
 * @Date 2023/7/19 14:08
 * @Version 1.0
 */
@RestController
@Api(tags = "手机端-会员API")
@RequestMapping(value = "/front/contamer")
public class FrontContamerController  {

    @Autowired
    private ContamerService  contamerService;

    @ApiOperation(value = "注册新用户")
    @PostMapping(value = "/register")
    public R register(@RequestBody @Valid ContamerAddReq req){
         //查询手机号是否被占用
        long count=this.contamerService.existsLoginId(req.getLoginId());
        if(count>0){
            return R.build(AckCode.USER_HAS_ACCOUNT);
        }

        if(!req.getPassword().equals(req.getPasswordConfirm())){
            return R.build(AckCode.SET_PASSWORD_INVALID);
        }

        Contamer contamer= ContamerConvert.INSTALCE.convert(req);
        contamer.setPassword(BCrypt.hashpw(contamer.getPassword()));
        contamer.setCreateBy(contamer.getLoginId());
        contamer.setStatus("0");

        boolean result = this.contamerService.save(contamer);

        return result?R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    @ApiOperation(value = "验证号码是否存在")
    @GetMapping(value = "/account/exists")
    public R existsPhone(String loginid){
        if(StrUtil.isBlank(loginid)){
            return R.build(AckCode.PHONE_NUMBER_NOTNULL);
        }
        //验证电话号码有效性
        String phoneExg="^0?(13|15|17|18|14|19)[0-9]{9}$";
        //定义一个正则表达式
        Pattern pattern = Pattern.compile(phoneExg);
        //创建一个匹配器，匹配正则表达式
        Matcher matcher = pattern.matcher(loginid);
        if(!matcher.matches()){
            return R.build(AckCode.PHONE_NUMBER_NOTNULL);
        }
        long count=this.contamerService.existsLoginId(loginid);
        R r=R.ok();
        if(count>0){
            r.setData( AckCode.USER_HAS_ACCOUNT.getMsg());
        }
        return r;
    }

}
